package com.bdqn.web; /**
 * <h3>项目名称:demo02222</h3>
 * <p>本API描述:${description}</p>
 * <p>@author : AliyZhang</p>
 * <p>@date : 2021-03-03 16:44</p>
 **/

import com.bdqn.entity.News;
import com.bdqn.service.Impl.NewsServiceImpl;
import com.bdqn.service.NewsService;
import com.bdqn.util.PageSupport;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "NewsServlet", value = "/news.do")
public class NewsServlet extends HttpServlet {
    //创建service对象，供调用
    private NewsService newsService=new NewsServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        /*
        用户要访问的功能:
        1.新闻列表分页展示
        2.增加新闻
        3.根据新闻id获取查询新闻信息
        key=list;---1
        key=add;---2
        key=showOne;---3
         */
        //获取用户访问的关键字key
        String key = request.getParameter("key");
        switch (key){
            case "list":
                list(request,response);
                break;
            case "add":
                add(request,response);
                break;
            case "showOne":
                showOne(request,response);
                break;

        }
    }

    private void add(HttpServletRequest request, HttpServletResponse response) {
    /*
    处理文件上传
    先判断请求是否包含文件上传信息
     */
        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            //创建新闻对象
            News news = new News();
            if(isMultipart){
                //创建文件上传的核心组件
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        /*
        文件上传后存到哪里?static/upload
        绑定绝对路径
         */
                String saveDirPath = request.getServletContext().getRealPath("static/upload");
                //判断上述目录是否存在，如果不存在就创建
                File saveDirFile = new File(saveDirPath);
                if(!saveDirFile.exists()){
                    //不存在就创建目录
                    saveDirFile.mkdirs();
                }
                //接收用户从前端传来的参数
                List<FileItem> items = upload.parseRequest(request);//解析用户的请求参数为list集合
                //通过迭代器遍历集合
                Iterator<FileItem> iterator = items.iterator();
                //遍历迭代器
                while (iterator.hasNext()){
                    //获取遍历到的元素
                    FileItem item = iterator.next();
                    //判断item是否为文件域参数
                    if(item.isFormField()){
                        //获取普通表单字段的名称
                        String fieldName = item.getFieldName();
                        //item是表单域
                        if("categoryId".equals(fieldName)){
                            //获取前端传来的普通字段数据，转换为整数后，为news对象的分类编号属性进行赋值，用utf-8字符集进行接收
                            news.setCategoryId(Integer.parseInt(item.getString("utf-8")));
                        }else if ("title".equals(fieldName)) {
                            news.setTitle(item.getString("utf-8"));
                        }else if ("author".equals(fieldName)){
                            news.setAuthor(item.getString("utf-8"));
                        }else if ("summary".equals(fieldName)){
                            news.setSummary(item.getString("utf-8"));
                        }else if ("content".equals(fieldName)){
                            news.setContent(item.getString("utf-8"));
                        }
                    }else {
                        //文件域
                        //处理文件上传   获取文件名称
                        String fileName = item.getName();
                        //创建文件对象，关联上传后的文件
                        File uploadFile = new File(saveDirPath, fileName);
                        item.write(uploadFile);//上传文件的操作
                        news.setPicPath(fileName);//设置文件名称
                    }
                }
            }
            news.setCreateDate(new Date());//设置新闻的创建日期
            //调用service的新闻增加方法
            NewsService newsService=new NewsServiceImpl();
            int count = newsService.addNews(news);
            if(count>0){
                response.sendRedirect("news.do?key=list");
            }else{
                response.getWriter().write("新闻增加失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void showOne(HttpServletRequest request, HttpServletResponse response) {
        News news = newsService.queryNewsById(Integer.parseInt(request.getParameter("id")));
        //把news对象存到page作用域中，键值对
        request.setAttribute("news",news);
        try {
            request.getRequestDispatcher("jsp/admin/newsDetailView.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void list(HttpServletRequest request, HttpServletResponse response) {
        int curPageNo=1;
        if(request.getParameter("curPageNo")!=null && !request.getParameter("curPageNo").equals("")){
            curPageNo=Integer.parseInt(request.getParameter("curPageNo"));
        }
        PageSupport<News> pageSupport= PageSupport.getInstance(curPageNo);
        newsService.queryPageNews(pageSupport);
        //我们所需的一切分页信息都已经在pageSupport里了
        request.setAttribute("page",pageSupport);
        //以转发的方式跳转到新闻列表页
        try {
            request.getRequestDispatcher("jsp/admin/newsDetailList.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
